package cn.itsource.pethome.pay.service.impl;

import cn.itsource.pethome.basic.service.impl.BaseServiceImpl;
import cn.itsource.pethome.order.domain.ProductOrder;
import cn.itsource.pethome.order.mapper.ProductOrderMapper;
import cn.itsource.pethome.pay.config.AlipayConfig;
import cn.itsource.pethome.pay.constant.PayConstants;
import cn.itsource.pethome.pay.domain.AlipayInfo;
import cn.itsource.pethome.pay.domain.PayBill;
import cn.itsource.pethome.pay.mapper.AlipayInfoMapper;
import cn.itsource.pethome.pay.mapper.PayBillMapper;
import cn.itsource.pethome.pay.service.IPayBillService;
import cn.itsource.pethome.quartz.domain.QuartzJobInfo;
import cn.itsource.pethome.quartz.service.IQuartzService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 支付单
 */
@Service
public class PayBillServiceImpl extends BaseServiceImpl<PayBill> implements IPayBillService {
    //支付信息mapper
    @Autowired
    private AlipayInfoMapper alipayInfoMapper;
    //支付单mapper
    @Autowired
    private PayBillMapper payBillMapper;
    //订单mapper
    @Autowired
    private ProductOrderMapper productOrderMapper;

    //定时任务service
    @Autowired
    private IQuartzService quartzService;

    /**
     * 去支付
     *
     * @return
     */
    @Override
    public String goPay(PayBill payBill) {
        try {
            //根据店铺id查询支付信息对象
            AlipayInfo alipayInfo =  alipayInfoMapper.loadByShopId(payBill.getShop().getId());

            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,alipayInfo.getAppid() , alipayInfo.getMerchant_private_key(), "json", AlipayConfig.charset,alipayInfo.getAlipay_public_key(), AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = payBill.getOrderSn();
            //付款金额，必填
            String total_amount = payBill.getMoney().toString();
            //订单名称，必填
            String subject = "宠物乐园";
            //商品描述，可空
            String body = payBill.getDigest();

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            return result;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 处理订单
     *
     * @param out_trade_no 订单号
     * @param trade_no     支付单号
     */
    @Override
    @Transactional
    public String handleOrder(String out_trade_no, String trade_no) {
        //根据订单号查询支付单
        PayBill payBill = payBillMapper.loadByOrderSn(out_trade_no);
        //判断支付订单状态如果不等于0 ，就结束支付宝多次请求
        if (payBill.getState()!=0){
            return "fail";
        }
        //设置返回状态时间
        payBill.setUpdateTime(new Date());
        //支付单号
        payBill.setUnionPaySn(trade_no);
        //转态为已支付
        payBill.setState(1);
        //进行修改
        payBillMapper.update(payBill);
        //处理订单(通过业务类型，还有业务键来定位到我要处理哪一张表中的哪一条数据)
        switch (payBill.getBusinessType()){
            case PayConstants.BUSINESSTYPE_PRODUCT:
                //通过业务id查询订单
                ProductOrder productOrder = productOrderMapper.loadById(payBill.getBusinessKey());//写sql
                //修改服务产品为待消费
                productOrder.setState(1);
                //修改
                productOrderMapper.update(productOrder);
                //支付完成之后清除定时器
                quartzService.removeJob(PayConstants.BUSINESSTYPE_PRODUCT + productOrder.getId());
                break;
            case PayConstants.BUSINESSTYPE_ADOPT:
                break;
            //........................
        }
        return "success";
    }
}
